package com.hqq.service.impl;

import cn.hutool.core.io.FileUtil;
import com.hqq.dao.WoocUserDao;
import com.hqq.dao.WoocVideoDao;
import com.hqq.domain.WoocVideo;
import com.hqq.domain.WoocVideoRemark;
import com.hqq.enums.SortTypeEnum;
import com.hqq.service.WoocVideoService;
import com.hqq.vo.VideoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * WoocVideoServiceImpl
 * Created by heqianqian on 2018/3/25.
 */
@Service
public class WoocVideoServiceImpl implements WoocVideoService {
    private static final Logger logger = LoggerFactory.getLogger(WoocVideoServiceImpl.class);
    private static final Integer START_COUNT = 0;
    private static final Integer VIDEO_COUNT = 10;
    private static final String SAVE_VIDEO_DIR = "/video/";
    private static final String SAVE_VIDEO_PROFILE_DIR = "/video_profile/";
    private static final String HOST_NAME = "http://localhost:8080";

    @Autowired
    private WoocVideoDao woocVideoDao;
    @Autowired
    private WoocUserDao woocUserDao;

    /**
     * 查询最热视频列表
     *
     * @return
     */
    @Override
    public List<WoocVideo> getHotVideos() {
        return woocVideoDao.listVideo(null, SortTypeEnum.HOTEST.toCode(), null, START_COUNT, VIDEO_COUNT);
    }

    /**
     * 查询最新视频列表
     *
     * @return
     */
    @Override
    public List<WoocVideo> getNewVideos() {
        return woocVideoDao.listVideo(null, SortTypeEnum.NEWEST.toCode(), null, START_COUNT, VIDEO_COUNT);
    }

    /**
     * 获取视频列表
     *
     * @param typeId
     * @param sortType
     * @param rankId
     * @return
     */
    @Override
    public List<WoocVideo> getVideoList(Long typeId, Long sortType, Long rankId, Integer pageNum) {
        Integer startCount = (pageNum - 1) * VIDEO_COUNT;
        return woocVideoDao.listVideo(typeId, sortType, rankId, startCount, VIDEO_COUNT);
    }

    @Override
    public VideoVO findVideo(Long videoId) {
        //FIXME 连表查询
        WoocVideo woocVideo = woocVideoDao.findVideoById(videoId);
        List<WoocVideoRemark> remarks = woocVideoDao.listRemark(videoId);
        for (WoocVideoRemark remark : remarks) {
            remark.setRemarkUserName(woocUserDao.findWoocUserById(remark.getRemarkUserId()).getUserName());
        }
        return VideoVO.builder()
                .video(woocVideo)
                .remarkList(remarks)
                .build();
    }

    /**
     * 发表评论
     *
     * @param userId
     * @param videoId
     * @param remarkContent
     */
    @Override
    public WoocVideoRemark publishRemark(Long userId, Long videoId, String remarkContent) {
        Objects.requireNonNull(userId, "用户id不可为空");
        Objects.requireNonNull(videoId, "视频id不可为空");
        Objects.requireNonNull(remarkContent, "评论内容不可为空");

        WoocVideoRemark remark = WoocVideoRemark.builder()
                .remarkUserId(userId)
                .remarkVideoId(videoId)
                .remarkContent(remarkContent)
                .remarkTime(new Date())
                .build();

        woocVideoDao.addWoocVideoDetail(remark);
        return remark;
    }

    @Override
    public WoocVideo insertVideo(WoocVideo woocVideo, MultipartFile file, MultipartFile profileFile) throws IOException {
        String path = Thread.currentThread().getContextClassLoader().getResource("log4j.xml").getPath();

        //保存视频
        String savePath = new StringBuffer().append(path.substring(0, path.indexOf("WEB-INF") - 1))
                .append(SAVE_VIDEO_DIR).append(file.getOriginalFilename()).toString();
        logger.debug("=========filePath:{}", savePath);
        File resultFile = FileUtil.writeFromStream(file.getInputStream(), savePath);
        logger.debug("===ResultFile:{},path:{}", resultFile.exists(), resultFile.getAbsolutePath());

        //保存封面
        String profilePath = new StringBuffer().append(path.substring(0, path.indexOf("WEB-INF") - 1))
                .append(SAVE_VIDEO_PROFILE_DIR).append(profileFile.getOriginalFilename()).toString();
        logger.debug("=========profilePath:{}", profilePath);
        File profileResultFile = FileUtil.writeFromStream(profileFile.getInputStream(), profilePath);
        logger.debug("===profileResultFile:{},path:{}", profileResultFile.exists(), profileResultFile.getAbsolutePath());

        woocVideo.setVideoUrl(HOST_NAME + SAVE_VIDEO_DIR + file.getOriginalFilename());
        woocVideo.setVideoProfileUrl(HOST_NAME + SAVE_VIDEO_PROFILE_DIR + profileFile.getOriginalFilename());
        woocVideo.setVideoUploadTime(new Date());
        woocVideo.setVideoSize(file.getSize());
        woocVideo.setVideoPlayCount(0L);

        woocVideoDao.insertVideo(woocVideo);
        return woocVideo;
    }

    /**
     * 删除视频
     *
     * @param videoId
     */
    @Override
    public void deleteVideo(Long videoId) {
        woocVideoDao.deleteVideoById(videoId);
        woocVideoDao.deleteVideoRemarkById(videoId);
    }
}
